package com.frontop.terminal.gangedsocket.core;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSON;
import com.frontop.terminal.entity.Message;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.frontop.terminal.vlcjplayer.Application.application;

/**
 * <p>
 * 延迟补偿
 * </p>
 *
 * @author :CCC
 * @since :2021-10-25
 **/
public class DelayOffset extends Thread {

    /**
     * 允许延迟范围
     */
    public static final int ALLOW_DELAY_SCOPE = 200;
    /**
     * 网络延迟记录
     */
    private static final List<Integer> DELAY_RECORD = new ArrayList<>(16);
    /**
     * 已进入准备状态
     */
    public static String PREPARE = "PREPARE";
    /**
     * 告知当前是延迟数据
     */
    public static String DELAY = "DELAY";
    /**
     * 下发主屏时间轴
     */
    public static String TIMELINE = "TIMELINE";
    public static PlayGangedClient PLAY_GANGED_CLIENT;
    /**
     * 运行标志
     */
    public static boolean ALIVE;
    /**
     * 主屏时间轴
     */
    public static Integer MAIN_SCREEN_TIMELINE;
    private static DelayOffset DELAYOFFSET;

    /**
     * 添加记录
     *
     * @param data 记录
     */
    public static void addDelayRecord(int data) {
        DELAY_RECORD.add(data);
    }

    public static void startDelayOffset() {
        if (ALIVE) {
            //只让一个线程工作，关闭线程
            ThreadUtil.interrupt(DELAYOFFSET, false);
        }
        ALIVE = true;
        DELAYOFFSET = new DelayOffset();
        ThreadUtil.execute(DELAYOFFSET);
    }

    /**
     * 计算延迟平均
     *
     * @return 延迟平均值
     */
    private int calculateNetworkDelay() {
        int sum = 0;
        int index = 1;
        System.out.print("[播放联动-延迟补偿]网络延迟\t");
        for (Integer integer : DELAY_RECORD) {
            sum += integer;
            System.out.print("数据" + index++ + ":" + integer + ",\t");
        }
        sum = (sum / DELAY_RECORD.size());
        System.out.println("平均值:" + sum);

        return sum;
    }

    private void adjustment() {
        while (true) {
            if (Objects.nonNull(MAIN_SCREEN_TIMELINE)) {
                //业务处理过程中的补偿时间
                int operationOffset = 600;
                //获取当前播放器时间轴
                float currentTimeline = application().mediaPlayer().status().time();
                System.out.println("[播放联动-延迟补偿]当前播放器时间轴:" + currentTimeline);
                //获取网络延迟平均值
                int sumDelay = calculateNetworkDelay() * 2;
                //当前视频和主屏进度差
                int delay = (int) (currentTimeline - MAIN_SCREEN_TIMELINE) - (sumDelay / 2);
                //进度超出允许的最大范围，并且当前进度大于主屏进度便后退
                if (delay > (ALLOW_DELAY_SCOPE + 500) && currentTimeline > MAIN_SCREEN_TIMELINE) {
                    //时间轴补偿
                    int timelineOffset = (int) (currentTimeline - MAIN_SCREEN_TIMELINE);

                    application().mediaPlayer().controls().skipTime(-(ALLOW_DELAY_SCOPE + sumDelay + timelineOffset));

                    System.out.println("[播放联动-延迟补偿]时间轴补偿:" + timelineOffset + "\t与主屏时间轴相差:" + (MAIN_SCREEN_TIMELINE - currentTimeline));
                    System.out.println("[播放联动-延迟补偿]当前进度相比主屏快" + ALLOW_DELAY_SCOPE + "+,已调节后退操作" + (ALLOW_DELAY_SCOPE + sumDelay + timelineOffset));
                } else if (delay < -ALLOW_DELAY_SCOPE && currentTimeline < MAIN_SCREEN_TIMELINE) {
                    //进度超出允许的最小范围，并且当前进度小于主屏进度便快进

                    //时间轴补偿
                    int timelineOffset = (int) (MAIN_SCREEN_TIMELINE - currentTimeline);
                    application().mediaPlayer().controls().skipTime((ALLOW_DELAY_SCOPE + sumDelay + timelineOffset + operationOffset));

                    System.out.println("[播放联动-延迟补偿]时间轴补偿:" + timelineOffset + "\t与主屏时间轴相差:" + (currentTimeline - MAIN_SCREEN_TIMELINE));
                    System.out.println("[播放联动-延迟补偿]当前进度相比主屏慢" + ALLOW_DELAY_SCOPE + "+,已调节快进操作" + (ALLOW_DELAY_SCOPE + sumDelay + timelineOffset + operationOffset));
                }
                MAIN_SCREEN_TIMELINE = null;
                DELAY_RECORD.removeAll(DELAY_RECORD);
                break;
            }
        }

    }

    private void prepare() {
        if (Objects.nonNull(PLAY_GANGED_CLIENT)) {
            Message message = new Message();
            message.setType(DELAY);

            int number = 3;
            for (int i = 0; i < number; i++) {
                message.setCommand(String.valueOf(System.currentTimeMillis()));
                PLAY_GANGED_CLIENT.send(JSON.toJSONString(message));
            }
        }
    }

    private void awaitTimeline() {
        if (Objects.nonNull(PLAY_GANGED_CLIENT)) {
            PLAY_GANGED_CLIENT.send(TIMELINE);
        }
    }

    @Override
    public void run() {
        //进入准备状态
        prepare();
        ThreadUtil.sleep(2000);
        //等待时间轴数据
        awaitTimeline();
        //纠正
        adjustment();

        ALIVE = false;
    }
}

